from app import constants, db
from app.models import News, Comment, CommentLike, User
from app.utils.common import user_login_check
from app.utils.response_code import RET
from . import news_blu
from flask import render_template, current_app, abort, g, jsonify, request
# 作者的关注与取消
@news_blu.route('/followed_user', methods=['POST'])
@user_login_check
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    action = request.json.get("action")
    user_id = request.json.get("user_id")

    if not all([action,user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    if action not in ['follow','unfollow']:
        return jsonify(errno=RET.PARAMERR,errmsg="操作不合法")

    try:
        T_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")

    if not T_user:
        return jsonify(errno=RET.DATAERR,errmsg="查无此人")
    try:
        if action == 'follow':
            if T_user.followers.filter(User.id == user.id).count()>0:
                return jsonify(errno=RET.DATAEXIST,errmsg="已经关注过了")
            T_user.followers.append(user)
        else:
            if T_user.followers.filter(User.id == user.id).count() > 0:
                T_user.followers.remove(user)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="关注失败")
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    return jsonify(errno=RET.OK,errmsg="关注成功")




# 点赞
@news_blu.route('/comment_like', methods=['POST'])
@user_login_check
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    news_id = request.json.get("news_id")

    if not all([comment_id,action,news_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if action not in ['add','remove']:
        return jsonify(errno=RET.PARAMERR,errmsg="操作不合法")

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据查询出错")

    if not comment:
        return jsonify(errno=RET.NODATA,errmsg="评论数不足")

    if action == "add":
        comment_like = CommentLike()
        comment_like.comment_id =comment_id
        comment_like.user_id = user.id
        db.session.add(comment_like)
        comment.like_count +=1
    else:
        comment_like = CommentLike.query.filter_by(comment_id=comment_id,user_id=user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count-=1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据提交失败")
    return jsonify(errno=RET.OK,errmsg="操作成功")


# 评论
@news_blu.route('/news_comment', methods=['POST'])
@user_login_check
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    json = request.get_json()
    news_id = json.get('news_id')
    comment_str = json.get('comment')
    parent_id = json.get("parent_id")
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻数据查询失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.parent_id = parent_id
    comment.content = comment_str

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存评论失败")

    return jsonify(errno=RET.OK, errmsg="评论成功",data=comment.to_dict())


# 收藏
@news_blu.route('/news_collect', methods=['POST'])
@user_login_check
def news_collect():
    user = g.user
    # 验证用户是否在线
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 验证参数
    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数传输错误")

    # 验证操作的合法性
    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg="操作不合法")

    # 从数据库查询数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    # 验证数据是否有效
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")

    # 操作分歧
    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    # 已经开启自动保存
    return jsonify(errno=RET.OK, errmsg="OK")


@news_blu.route('/<int:news_id>')
@user_login_check
def news_details(news_id):
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)

    news.clicks += 1

    # 新闻排行数据
    try:
        neWs = News.query.order_by(News.clicks.desc()).limit((constants.CLICK_RANK_MAX_NEWS - 2))
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="新闻获取异常")
    click_news_list = [i.to_dict() for i in neWs]

    click_rank_class = ['first', 'second', 'third']
    for i in range(7):
        click_rank_class.append('')
    # 判断用户是否收藏
    is_collected = False
    is_followed = False

    if g.user:
        if  news in (g.user.collection_news):
            is_collected = True
        if  news.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed = True


    # 评论列表
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    comment_like_ids = []
    # 判断是否在点赞收藏表中
    if g.user:
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) :
                    comment_like = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                            CommentLike.user_id == g.user.id).all()
                    comment_like_ids = [i.comment_id for i in comment_like]

        except Exception as e:
            current_app.logger.error(e)
    # 给评价列表中每条评价添加点赞属性
    comment_list = []
    for i in comments if comments else []:
        comment_dict = i.to_dict()
        comment_dict['is_like'] = False

        if g.user and i.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)


    data = {
        "news": news.to_dict(),
        "user_info": g.user.to_dict() if g.user else '',
        'click_rank_class': click_rank_class,
        'click_news_list': click_news_list,
        'is_collected':is_collected,
        'comments':comment_list,
        "is_followed":is_followed
    }



    return render_template('news/detail.html', data=data)
